const mongoose = require('mongoose');

class Database {
  constructor() {
    this.connection = null;
  }

  async connect() {
    try {
      const mongoUri = process.env.MONGODB_URI || 'mongodb://localhost:27017/saas_multitenant';
      
      const options = {
        maxPoolSize: 10,
        serverSelectionTimeoutMS: 5000,
        socketTimeoutMS: 45000
      };

      this.connection = await mongoose.connect(mongoUri, options);
      
      console.log('✅ MongoDB connected successfully');
      
      // 监听连接事件
      mongoose.connection.on('error', (err) => {
        console.error('❌ MongoDB connection error:', err);
      });

      mongoose.connection.on('disconnected', () => {
        console.log('⚠️ MongoDB disconnected');
      });

      // 优雅关闭
      process.on('SIGINT', async () => {
        await mongoose.connection.close();
        console.log('📴 MongoDB connection closed through app termination');
        process.exit(0);
      });

      return this.connection;
    } catch (error) {
      console.error('❌ MongoDB connection failed:', error);
      throw error; // 不要直接退出进程，让调用者处理错误
    }
  }

  async disconnect() {
    if (this.connection) {
      await mongoose.connection.close();
      console.log('📴 MongoDB connection closed');
    }
  }

  getConnection() {
    return this.connection;
  }

  // 创建租户相关的索引
  async createIndexes() {
    try {
      // 为所有集合的 tenantId 字段创建索引
      const collections = ['users', 'tenants'];
      
      for (const collectionName of collections) {
        const collection = mongoose.connection.db.collection(collectionName);
        await collection.createIndex({ tenantId: 1 });
        console.log(`✅ Created tenantId index for ${collectionName}`);
      }

      // 为租户集合创建唯一索引
      const tenantsCollection = mongoose.connection.db.collection('tenants');
      await tenantsCollection.createIndex({ tenantId: 1 }, { unique: true });
      await tenantsCollection.createIndex({ domain: 1 }, { unique: true });
      
      // 为用户集合创建复合索引
      const usersCollection = mongoose.connection.db.collection('users');
      await usersCollection.createIndex({ tenantId: 1, email: 1 }, { unique: true });
      
      console.log('✅ All database indexes created successfully');
    } catch (error) {
      console.error('❌ Error creating indexes:', error);
    }
  }
}

// 导出连接函数
const connectDB = async () => {
  const db = new Database();
  return await db.connect();
};

module.exports = { Database, connectDB };